package com.demo.user.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.demo.user.application.assembler.UserConverter;
import com.demo.user.config.AppEnv;
import com.demo.user.dao.LoginUserDaoJpa;
import com.demo.user.dto.UserDetailDto;
import com.demo.user.dto.UserDto;
import com.demo.user.dto.UserPageDto;
import com.demo.user.dto.UserPageParamDto;
import com.demo.user.entity.User;
import com.demo.user.exception.BizServiceException;
import com.demo.user.exception.EErrorCode;
import com.demo.user.mapper.UserMapper;
import com.demo.user.repository.UserRepository;
import com.demo.user.service.JpaUserService;
import com.demo.user.service.UserService;
import com.demo.user.util.page.BasePaginationRsp;
import com.demo.user.vo.LoginVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.criteria.*;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 用户(BlUser)表服务实现类
 *
 * @author makejava
 * @since 2023-03-24 14:32:24
 */
@Service("userService")
public class UserServiceImpl implements UserService {
  @Resource
  private UserMapper userMapper;
  @Resource
  private UserConverter userConverter;
  @Resource
  private AppEnv appEnv;

  //静态插入数据:通用方法
  @Override
  public int insertUser(User user) {
    User userById = userMapper.queryUserByUid(user.getUid());
    if (userById !=null){
      throw new RuntimeException("id自增，默认可不传id，是唯一主键，已经存在："+user.getUid());
    }
    user.setUpdateTime(new Date());
    return userMapper.insertUser(user);
  }
  @Override
  //动态插入数据: mysql用法，id自增
  public int insertUserMysql(User user) {
    return userMapper.insertUserMysql(user);
  }

  @Override
  //mybatis批量插入数据:mysql用法，id自增
  public int mysqlBatchSaveUser(List<User> userEntities) {
    return userMapper.mysqlBatchSaveUser(userEntities);
  }

  @Override
  //按id查询用户
  public User queryUserById(Long id) {
    return userMapper.queryUserByUid(id);
  }
  @Override
  //查询所有用户
  public List<Map<String, Object>> queryAllUser() {
    return userMapper.queryAllUser();
  }

//  /**
//   * 获取分页结果
//   * @param pageNum 页码值
//   * @param pageSize 每页显示条数
//   */
//  @Override
//  public List<User> getPagingResults(int pageNum, int pageSize) {
//    //第一个参数是页码值，第二个参数是每页显示条数，第三个参数默认查询总数count
//    //获取第pageNum页，每页pageSize条内容，默认查询总数count
//    PageHelper.startPage(pageNum, pageSize);
//    //紧跟着的第一个select方法会被分页
//    return userMapper.queryAllUser();
//  }

//  /**
//   * 获取分页结果及分页信息
//   * @param pageNum 页码值
//   * @param pageSize 每页显示条数
//   */
//  @Override
//  public PageInfo<User> queryPageInfo(int pageNum, int pageSize) {
//    //第一个参数是页码值，第二个参数是每页显示条数，第三个参数默认查询总数count
//    //获取第pageNum页，每页pageSize条内容，默认查询总数count
//    PageHelper.startPage(pageNum, pageSize,true);
//    //紧跟着的第一个select方法会被分页
//    List<User> userEntities = userMapper.queryAllUser();
//
//    //分页信息
//    PageInfo<User> pageInfo = new PageInfo<User>(userEntities);
//
//    //打印分页信息
//    System.out.println("数据总数：" + pageInfo.getTotal());
//    System.out.println("数据总页数：" + pageInfo.getPages());
//    System.out.println("进入第一页：" + pageInfo.getNavigateFirstPage());
//    System.out.println("进入最后一页：" + pageInfo.getNavigateLastPage());
//
//    for (User user : pageInfo.getList()) {
//      System.out.println(user);
//    }
//    return pageInfo;
//  }
  @Override
  //更新数据-改数据
  public int updateUser(User user) {
    user.setUpdateTime(new Date());
    return userMapper.updateUser(user);
  }
  @Override
  //删除数据
  public int delUser(Integer id) {
    return userMapper.delUser(id);
  }

  @Override
  //按id查询用户
  public User selectByPrimaryKey(Long id) {
    return userMapper.selectByPrimaryKey(id);
  }

  @Override
  //用户详情-参数转换
  public UserDetailDto detail(Long id) {
    User user = this.selectByPrimaryKey(id);
    if (user == null) {
      throw new BizServiceException(EErrorCode.DATA_NOT_FUND_ERROR);
    }
    UserDetailDto userDetailDto = userConverter.toDto(user);
//    AdminRole role = adminRoleMapper.getByAdminCode(code);
//    if (role != null) {
//      adminDetailDto.setRoleCode(role.getCode());
//      adminDetailDto.setRoleName(role.getName());
//    }
    return userDetailDto;
  }

  /**
   * 用户分页数据
   * @param pageParam
   * @return
   */
  @Override
  public BasePaginationRsp<UserPageDto> page(UserPageParamDto pageParam) {
    PageHelper.startPage(pageParam.getPageNo(), pageParam.getPageSize())
            .setOrderBy(Optional.ofNullable(pageParam.getFullOrderBy()).orElse("a.reg_time desc"));
    PageInfo<User> page = new PageInfo(userMapper.page(pageParam));
    List<UserPageDto> dtos = userConverter.toDtos(page.getList());
    System.out.print(appEnv.isLocalEnv());
    if (CollectionUtils.isNotEmpty(dtos)) {
//      List<String> adminCodes = dtos.stream()
//              .map(UserPageDto::getUid).collect(Collectors.toList());
//      List<AdminRole> roles = adminRoleMapper.listByAdminCodes(adminCodes);
//      if (CollectionUtils.isNotEmpty(roles)) {
//        Map<String, AdminRole> roleMap = roles.stream().collect(Collectors.toMap(AdminRole::getAdminCode, Function.identity()));
//        dtos.forEach(
//                a -> a.setRoleName(Optional.ofNullable(roleMap.get(a.getCode())).orElse(new AdminRole()).getName())
//        );
//      }
    }

    return BasePaginationRsp.fromPageInfo(page, dtos);
  }
}
